package com.nbjtjc.safe.service.report;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.util.PoiMergeCellUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.bean.MyCache;
import com.nbjtjc.safe.mapper.danger.*;
import com.nbjtjc.safe.mapper.sys.SysFileMapper;
import com.nbjtjc.safe.model.danger.*;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.service.sys.SysDeptService;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

/**
 * @auther guqianbin
 * @date 2018/4/28 8:36
 **/
@Service
public class DangerReportService {

    @Autowired
    private DangerSafePlanListMapper dangerSafePlanListMapper;

    @Autowired
    private DangerSafePlanMapper dangerSafePlanMapper;

    @Autowired
    private DangerInspectPublicMapper dangerInspectPublicMapper;

    @Autowired
    private DangerInspectListPublicMapper dangerInspectListPublicMapper;
    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private DangerReformReplyMapper dangerReformReplyMapper;
    @Autowired
    private DangerReformSheetMapper dangerReformSheetMapper;
    @Autowired
    private SysFileMapper sysFileMapper;
    //TODO 临时文件的清理
    @Value("${file.path.tempPath}")
    private String fileTempPath;

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private MyCache mycache;
    /**
     * 年度安全检查计划
     *
     * @param response
     * @param dangerSafePlanId
     */
    public void dangerSafePlanExcel(HttpServletResponse response, int dangerSafePlanId) {
        try {
            DangerSafePlan dangerSafePlan = dangerSafePlanMapper.selectByPrimaryKey(dangerSafePlanId);
            if (ObjectUtil.isNull(dangerSafePlan)) {
                return;
            }
            DangerSafePlanList dangerSafePlanList = new DangerSafePlanList(dangerSafePlanId);
            List<DangerSafePlanList> dangerSafePlanLists = dangerSafePlanListMapper.search(dangerSafePlanList);
            Map<String, Object> map = new HashMap<String, Object>();
            if (CollectionUtil.isEmpty(dangerSafePlanLists)) {
                map.put("planLists", new ArrayList<>());
            } else {
                map.put("planLists", dangerSafePlanLists);
            }
            map.put("planName", dangerSafePlan.getName());
            map.put("docNum", " ");
            map.put("recordNum", " ");

            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/danger/dangerSafePlan.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "dangerSafePlan-" + dangerSafePlanId + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            String filePath = fileTempPath + "emgGoods-" + emgPlanPublicId + "-" + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 该部门，当前年度所有检查的汇总
     *
     * @param response
     */
    public void dangerInspectPublic(HttpServletResponse response, int year) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            String yearStart = year + "-01-01";
            String yearEnd = year + "-12-31";
            Date startDate = DateUtil.parse(yearStart);
            Date endDate = DateUtil.parse(yearEnd);
            DangerInspectPublic dangerInspectPublic = new DangerInspectPublic();
            dangerInspectPublic.setStartDate(startDate);
            dangerInspectPublic.setEndDate(endDate);
            dangerInspectPublic.setPublicDeptId(MyShiroUtils.getCompanyId());
            List<DangerInspectPublic> dangerInspectPublics = dangerInspectPublicMapper.search(dangerInspectPublic, null);
            if (CollectionUtil.isEmpty(dangerInspectPublics)) {
                map.put("planPublicLists", new ArrayList<>());
            } else {
                map.put("planPublicLists", dangerInspectPublics);
                for (int i = 0; i < dangerInspectPublics.size(); i++) {
                    dangerInspectPublics.get(i).setNum(i + 1);
                }
            }
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/danger/dangerInspectPublic.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "dangerSafePlan-" + MyShiroUtils.getCompanyId() + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
//            String filePath = fileTempPath + "emgGoods-" + emgPlanPublicId + "-" + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取某次检查的详情的excel
     *
     * @param response
     * @param dangerInspectPublicId
     */
    public void dangerInspectPublicDetailExcel(HttpServletResponse response, int dangerInspectPublicId) {
        try {
            Map<String, Object> map = new HashMap<>();
            DangerInspectPublic dangerInspectPublic = new DangerInspectPublic(dangerInspectPublicId);
            dangerInspectPublic = dangerInspectPublicMapper.getDetail(dangerInspectPublic);
            if (ObjectUtil.isNull(dangerInspectPublic)) {
                return;
            }
            if(CollectionUtil.isNotEmpty(dangerInspectPublic.getDangerInspectListPublicList())){
                for(int i=0;i<dangerInspectPublic.getDangerInspectListPublicList().size();i++){
                    dangerInspectPublic.getDangerInspectListPublicList().get(i).setNum(i+1);
                }
            }
            if(dangerInspectPublic.getNeedFeedback().equals(1)){
                map.put("needFeedback","是");
            }else{
                map.put("needFeedback","否");
            }
            if(ObjectUtil.isNotNull(dangerInspectPublic.getTargetContractorUserId())){
                dangerInspectPublic.setTargetContractorUserName(
                        mycache.getUserName(dangerInspectPublic.getTargetContractorUserId()));
            }
            map.put("ip", dangerInspectPublic);
            if (CollectionUtil.isEmpty(dangerInspectPublic.getDangerInspectListPublicList())) {
                map.put("ilp", new ArrayList<>());
            } else {
                map.put("ilp", dangerInspectPublic.getDangerInspectListPublicList());
            }
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/danger/dangerInspectPublicDetail.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
            File savefile = new File("d://excel");
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "dangerSafePlanPublicDetail-" +
                    dangerInspectPublicId + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            insertImages(new File(filePath), dangerInspectPublic);
            fileUtil.writeFile(response, new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向文件追加图片，一行2张图片
     *
     * @param excel               excel文件
     * @param dangerInspectPublic
     * @throws IOException
     */
    private void insertImages(File excel, DangerInspectPublic dangerInspectPublic) throws IOException {
        List<DangerInspectListPublic> dangerInspectListPublics = dangerInspectPublic.getDangerInspectListPublicList();
        List<SysFile> sysFiles = new ArrayList<>();
        SysFile sysFile = new SysFile();
        for (int i = 0; i < dangerInspectListPublics.size(); i++) {
            sysFile.setContentId(dangerInspectListPublics.get(i).getId());
            sysFile.setContentType(4);
            List<SysFile> files = sysFileMapper.select(sysFile);
            sysFiles.addAll(files);
        }
        if (CollectionUtil.isNotEmpty(sysFiles)) {
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(excel));
            Sheet sheet = xssfWorkbook.getSheetAt(0);
            XSSFDrawing xssfDrawing = (XSSFDrawing) sheet.createDrawingPatriarch();
            int lastRowNum = sheet.getLastRowNum();
            int j = 0;
            for (int i = 0; i < sysFiles.size(); i++) {
                int y1 = lastRowNum + 2 + j * 18;
                int y2 = lastRowNum + 2 + (j + 1) * 18;
                XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255
                        , 0, y1 + j, 3, y2 + j);
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                BufferedImage bufferImg = ImageIO.read(fileUtil.getFile(sysFiles.get(i)));
                ImageIO.write(bufferImg, fileUtil.getFileType(sysFiles.get(i)), byteArrayOut);
                xssfDrawing.createPicture(anchor, xssfWorkbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                i = i + 1;
                if (i >= sysFiles.size())
                    break;
                XSSFClientAnchor anchor2 = new XSSFClientAnchor(0, 0, 255, 255
                        , 4, y1 + j, 7, y2 + j);
                ByteArrayOutputStream byteArrayOut2 = new ByteArrayOutputStream();
                BufferedImage bufferImg2 = ImageIO.read(fileUtil.getFile(sysFiles.get(i)));
                ImageIO.write(bufferImg2, fileUtil.getFileType(sysFiles.get(i)), byteArrayOut2);
                xssfDrawing.createPicture(anchor2, xssfWorkbook.addPicture(byteArrayOut2.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                j++;
            }
            FileOutputStream fileOutputStream = new FileOutputStream(excel);
            xssfWorkbook.write(fileOutputStream);
            fileOutputStream.close();
        }
    }


    /**
     * 返回隐患整改单的excel模板
     *
     * @param response
     * @param dangerReformReplyId
     */
    public void dangerReformReplyExcel(HttpServletResponse response, int dangerReformReplyId) {
        try {
            Map<String, Object> map = new HashMap<>();
            DangerReformReply dangerReformReply=dangerReformReplyMapper.selectByPrimaryKey(dangerReformReplyId);

            DangerInspectPublic dangerInspectPublic = new DangerInspectPublic(dangerReformReply.getDangerInspectPublicId());
            dangerInspectPublic = dangerInspectPublicMapper.getDetail(dangerInspectPublic);
            if (ObjectUtil.isNull(dangerInspectPublic)) {
                return;
            }
            DangerReformSheet dangerReformSheet=new DangerReformSheet();
            dangerReformSheet.setDangerInspectPublicId(dangerInspectPublic.getId());
            dangerReformSheet.setApplyUserId(dangerReformReply.getUserId());
            List<DangerReformSheet> dangerReformSheets=dangerReformSheetMapper.select(dangerReformSheet);
            if(CollectionUtil.isNotEmpty(dangerReformSheets)){
                //todo 添加验收时间
            }
            map.put("ip", dangerInspectPublic);
            map.put("reformReply",dangerReformReply);
            DangerInspectListPublic dangerInspectListPublic = new DangerInspectListPublic();
            dangerInspectListPublic.setInspectPublicId(dangerInspectPublic.getId());
            dangerInspectListPublic.setApplyUserId(dangerReformReply.getUserId());
//            dangerInspectListPublic.setNeedChange(1);
            List<DangerInspectListPublic> dangerInspectListPublics =
                    dangerInspectListPublicMapper.search(dangerInspectListPublic);
            dangerInspectPublic.setDangerInspectListPublicList(dangerInspectListPublics);
            if (CollectionUtil.isEmpty(dangerInspectListPublics)) {
                map.put("ilp", new ArrayList<>());
            } else {
                map.put("ilp", dangerInspectListPublics);
            }
            TemplateExportParams params = new TemplateExportParams(
                    "reportTemplates/danger/dangerReformReply.xlsx");
            params.setHeadingStartRow(0);
            params.setHeadingRows(5);

            Workbook workbook = ExcelExportUtil.exportExcel(params, map);

            PoiMergeCellUtil.mergeCells(workbook.getSheetAt(0), 5, 0, 7);
            File savefile = new File(fileTempPath);
            if (!savefile.exists()) {
                savefile.mkdirs();
            }
            String filePath = fileTempPath + "dangerSafePlanPublicDetail-" +
                    dangerInspectPublic.getId() + "-" + MyShiroUtils.getSessionUserId() + ".xlsx";
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            fos.close();
            insertReformReplyImages(new File(filePath), dangerInspectPublic);
            fileUtil.writeFile(response,new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 想整改后的回执单插入隐患照片和整改后的照片
     *
     * @param excel
     * @param dangerInspectPublic
     */
    private void insertReformReplyImages(File excel, DangerInspectPublic dangerInspectPublic) throws IOException {
        List<DangerInspectListPublic> dangerInspectListPublics =
                dangerInspectPublic.getDangerInspectListPublicList();
        List<SysFile> dangerImages = new ArrayList<>();
        List<SysFile> reformImages = new ArrayList<>();
        SysFile sysFile = new SysFile();
        for (int i = 0; i < dangerInspectListPublics.size(); i++) {
            dangerInspectListPublics.get(i).setNum(i + 1);
            sysFile.setContentId(dangerInspectListPublics.get(i).getId());
            sysFile.setContentType(4);
            List<SysFile> files = sysFileMapper.select(sysFile);
            dangerImages.addAll(files);
            sysFile.setContentType(6);
            files = sysFileMapper.select(sysFile);
            reformImages.addAll(files);
        }
        dangerImages.addAll(reformImages);
        if (CollectionUtil.isNotEmpty(dangerImages)) {
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(excel));
            Sheet sheet = xssfWorkbook.getSheetAt(0);
            XSSFDrawing xssfDrawing = (XSSFDrawing) sheet.createDrawingPatriarch();
            int lastRowNum = sheet.getLastRowNum();
            int j = 0;
            for (int i = 0; i < dangerImages.size(); i++) {
                int y1 = lastRowNum + 2 + j * 18;
                int y2 = lastRowNum + 2 + (j + 1) * 18;
                XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 255, 255
                        , 0, y1 + j, 3, y2 + j);
                ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
                BufferedImage bufferImg = ImageIO.read(fileUtil.getFile(dangerImages.get(i)));
                ImageIO.write(bufferImg, fileUtil.getFileType(dangerImages.get(i)), byteArrayOut);
                xssfDrawing.createPicture(anchor, xssfWorkbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                i = i + 1;
                if (i >= dangerImages.size())
                    break;
                XSSFClientAnchor anchor2 = new XSSFClientAnchor(0, 0, 255, 255
                        , 4, y1 + j, 7, y2 + j);
                ByteArrayOutputStream byteArrayOut2 = new ByteArrayOutputStream();
                BufferedImage bufferImg2 = ImageIO.read(fileUtil.getFile(dangerImages.get(i)));
                ImageIO.write(bufferImg2, fileUtil.getFileType(dangerImages.get(i)), byteArrayOut2);
                xssfDrawing.createPicture(anchor2, xssfWorkbook.addPicture(byteArrayOut2.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
                j++;
            }
            FileOutputStream fileOutputStream = new FileOutputStream(excel);
            xssfWorkbook.write(fileOutputStream);
            fileOutputStream.close();
        }
    }
}
